package org.quadraspace.resource;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quadraspace.model.Mote;
import org.quadraspace.model.MoteUtil;
import org.quadraspace.service.MoteRepository;

import com.sun.jersey.api.NotFoundException;

@Path("/motes/{moteID}")
@Produces(MediaType.APPLICATION_XML)
@Consumes(MediaType.APPLICATION_XML)
public class MoteResource {
	private static final Log logger = LogFactory.getLog(MoteResource.class);
	private MoteRepository repository = null;

	@GET
	public Mote getIt(@PathParam("moteID") String moteId) {
		Mote toRet = repository.getMoteWithID(moteId);
		if (toRet == null) {
			logger.trace("mote with id: "+ moteId +" was not found!");
			throw new NotFoundException();
		}
		logger.trace("returning mote with id: "+ toRet.getId());
		return toRet;
	}

	@DELETE
	public void deleteIt(@PathParam("moteID") String moteId) {
		logger.debug("deleting mote with id: "+ moteId);
		repository.deleteMoteWithId(moteId);
	}
	
	@PUT
	public void updateIt(@PathParam("moteID") String moteId, Mote toSave) {
		toSave.setId(moteId);
		Mote present = repository.getMoteWithID(moteId);
		if (present == null) {
			logger.trace("mote with id: "+ moteId +" was not found!");
			throw new NotFoundException();
		}

		logger.trace("about to merge motes...");
		MoteUtil.mergeMotes(toSave, present);

		logger.trace("saving mote with id: "+moteId);
		repository.registerMote(present);
	}
	
	public void setRepository(MoteRepository repository) {
		this.repository = repository;
	}
}
